package cc.uncarbon.module.custom.service;

import cc.uncarbon.framework.core.constant.HelioConstant;
import cc.uncarbon.framework.core.exception.BusinessException;
import cc.uncarbon.framework.core.page.PageParam;
import com.yanrumiao.entity.PageResult;
import cc.uncarbon.module.custom.entity.ItemBannerEntity;
import cc.uncarbon.module.custom.mapper.ItemBannerMapper;
import cc.uncarbon.module.custom.model.request.AdminItemBannerInsertOrUpdateDTO;
import cc.uncarbon.module.custom.model.request.AdminItemBannerListDTO;
import cc.uncarbon.module.custom.model.response.ItemBannerBO;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;


/**
 * 数据表注释
 */
@RequiredArgsConstructor
@Service
@Slf4j
public class ItemBannerService {

    private final ItemBannerMapper itemBannerMapper;


    /**
     * 后台管理-分页列表
     */
    public PageResult<ItemBannerBO> adminList(PageParam pageParam, AdminItemBannerListDTO dto) {
        Page<ItemBannerEntity> entityPage = itemBannerMapper.selectPage(
                new Page<>(pageParam.getPageNum(), pageParam.getPageSize()),
                new QueryWrapper<ItemBannerEntity>()
                        .lambda()
                        // 状态（0禁用，1正常
                        .eq(ObjectUtil.isNotNull(dto.getStatus()), ItemBannerEntity::getStatus, dto.getStatus())
                        // 店铺id
                        .eq(ObjectUtil.isNotNull(dto.getStoreId()), ItemBannerEntity::getStoreId, dto.getStoreId())
                        // 名称
                        .like(CharSequenceUtil.isNotBlank(dto.getName()), ItemBannerEntity::getName, CharSequenceUtil.cleanBlank(dto.getName()))
                        // 图片地址
                        .like(CharSequenceUtil.isNotBlank(dto.getUrl()), ItemBannerEntity::getUrl, CharSequenceUtil.cleanBlank(dto.getUrl()))
                        // 项目id
                        .eq(ObjectUtil.isNotNull(dto.getItemId()), ItemBannerEntity::getItemId, dto.getItemId())
                        // 排序
                        .eq(ObjectUtil.isNotNull(dto.getSort()), ItemBannerEntity::getSort, dto.getSort())
                        // 时间区间
                        .between(ObjectUtil.isNotNull(dto.getBeginAt()) && ObjectUtil.isNotNull(dto.getEndAt()), ItemBannerEntity::getCreatedAt, dto.getBeginAt(), dto.getEndAt())
                        // 排序
                        .orderByDesc(ItemBannerEntity::getCreatedAt)
        );

        return this.entityPage2BOPage(entityPage);
    }

    /**
     * 根据 ID 取详情
     *
     * @param id 主键ID
     * @return null or BO
     */
    public ItemBannerBO getOneById(Long id) {
        return this.getOneById(id, false);
    }

    /**
     * 根据 ID 取详情
     *
     * @param id 主键ID
     * @param throwIfInvalidId 是否在 ID 无效时抛出异常
     * @return null or BO
     */
    public ItemBannerBO getOneById(Long id, boolean throwIfInvalidId) throws BusinessException {
        ItemBannerEntity entity = itemBannerMapper.selectById(id);
        if (throwIfInvalidId && entity == null) {
            throw new BusinessException(400, "无效数据表注释ID");
        }

        return this.entity2BO(entity);
    }

    /**
     * 后台管理-新增
     */
    @Transactional(rollbackFor = Exception.class)
    public Long adminInsert(AdminItemBannerInsertOrUpdateDTO dto) {
        log.info("[后台管理-数据表注释-新增] >> DTO={}", dto);
        this.checkExistence(dto);

        dto.setId(null);
        ItemBannerEntity entity = new ItemBannerEntity();
        BeanUtil.copyProperties(dto, entity);

        itemBannerMapper.insert(entity);

        return entity.getId();
    }

    /**
     * 后台管理-编辑
     */
    @Transactional(rollbackFor = Exception.class)
    public void adminUpdate(AdminItemBannerInsertOrUpdateDTO dto) {
        log.info("[后台管理-数据表注释-编辑] >> DTO={}", dto);
        this.checkExistence(dto);

        ItemBannerEntity entity = new ItemBannerEntity();
        BeanUtil.copyProperties(dto, entity);

        itemBannerMapper.updateById(entity);
    }

    /**
     * 后台管理-删除
     */
    @Transactional(rollbackFor = Exception.class)
    public void adminDelete(Collection<Long> ids) {
        log.info("[后台管理-数据表注释-删除] >> ids={}", ids);
        itemBannerMapper.deleteBatchIds(ids);
    }


    /*
    ----------------------------------------------------------------
                        私有方法 private methods
    ----------------------------------------------------------------
     */

    /**
     * 实体转 BO
     *
     * @param entity 实体
     * @return BO
     */
    private ItemBannerBO entity2BO(ItemBannerEntity entity) {
        if (entity == null) {
            return null;
        }

        ItemBannerBO bo = new ItemBannerBO();
        BeanUtil.copyProperties(entity, bo);

        // 可以在此处为BO填充字段

        return bo;
    }

    /**
     * 实体 List 转 BO List
     *
     * @param entityList 实体 List
     * @return BO List
     */
    private List<ItemBannerBO> entityList2BOs(List<ItemBannerEntity> entityList) {
        if (CollUtil.isEmpty(entityList)) {
            return Collections.emptyList();
        }

        // 深拷贝
        List<ItemBannerBO> ret = new ArrayList<>(entityList.size());
        entityList.forEach(
            entity -> ret.add(this.entity2BO(entity))
        );

        return ret;
    }

    /**
     * 实体分页转 BO 分页
     *
     * @param entityPage 实体分页
     * @return BO 分页
     */
    private PageResult<ItemBannerBO> entityPage2BOPage(Page<ItemBannerEntity> entityPage) {
        return new PageResult<ItemBannerBO>()
            .setCurrent((int) entityPage.getCurrent())
            .setSize((int) entityPage.getSize())
            .setTotal((int) entityPage.getTotal())
            .setRecords(this.entityList2BOs(entityPage.getRecords()));
    }

    /**
     * 检查是否已存在同名数据
     *
     * @param dto DTO
     */
    private void checkExistence(AdminItemBannerInsertOrUpdateDTO dto) {
        /*
        可以根据自己业务需要，解禁这段代码，修改判断条件和文案

        ItemBannerEntity existingEntity = itemBannerMapper.selectOne(
                new QueryWrapper<ItemBannerEntity>()
                        .lambda()
                        .select(ItemBannerEntity::getId)
                        .eq(ItemBannerEntity::getTitle, dto.getTitle())
                        .last(HelioConstant.CRUD.SQL_LIMIT_1)
        );

        if (existingEntity != null && !existingEntity.getId().equals(dto.getId())) {
            throw new BusinessException(400, "已存在相同数据表注释，请重新输入");
        }
        */
    }

}
